package com.htiiot.activemq.db;

import java.sql.Connection;
import java.sql.SQLException;

import com.htiiot.activemq.dbConfig.DbConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

/**
 * Created by sunmya on 2016/10/14.
 */
public class DbConnectionPool {
	// 连接池
	private HikariDataSource dataSource;
	private static DbConnectionPool dbPool;
	private static DbConfig dbConfig;


	public static DbConnectionPool getPool(DbConfig config) {

		dbConfig = config;
		if (dbPool == null) {
			dbPool = new DbConnectionPool();
		}

		return dbPool;
	}

	public DbConnectionPool() {

		// 连接池配置信息
		String dbUrl = dbConfig.getDbUrl();
		String dbUser = dbConfig.getDbUser();
		String dbPassword = dbConfig.getDbPassword();
		String driverClassName = dbConfig.getDriverClassName();
		
		HikariConfig config = new HikariConfig();
		config.setJdbcUrl(dbUrl);
		if (dbUser != null && dbUser.length() > 0) {
			config.setUsername(dbUser);
		}

		if (dbPassword != null && dbPassword.length() > 0) {
			config.setPassword(dbPassword);
		}

		if (driverClassName != null && driverClassName.length() > 0) {
			config.setDriverClassName(driverClassName);
		}

		config.setMaximumPoolSize(10);
		config.setIdleTimeout(1200000);
		config.setConnectionTimeout(30000);
		config.addDataSourceProperty("cachePrepStmts", "true");
		config.addDataSourceProperty("prepStmtCacheSize", "250");
		config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

		// 链接池初始化
		setDataSource(new HikariDataSource(config));
	}

	// 获取链接
	public Connection getConnection() {
		Connection con = null;
		try {
			con = getDataSource().getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}

	// 关闭连接池
	public void close() {
		dataSource.close();
	}

	public HikariDataSource getDataSource() {
		return dataSource;
	}

	private void setDataSource(HikariDataSource dataSource) {
		this.dataSource = dataSource;
	}
}
